package com.ossfk.jt808.codec;

import java.util.List;

import com.ossfk.jt808.pojo.Jt808Msg;
import com.ossfk.jt808.pojo.Jt808MsgHeader;
import com.ossfk.jt808.utils.Jt808Utils;
import com.ossfk.net.utils.HexStringUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Jt808Decoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		// 消息头的最小字节数
		if (in.readableBytes() < Jt808MsgHeader.HEADER_MIN_LENGTH) {
			return;
		}
		
		Jt808Msg jt808Msg = new Jt808Msg();
		byte[] data = new byte[in.readableBytes()];
		in.readBytes(data);

		System.out.println("收到："+HexStringUtils.toHexString(data));
		// 0. 转义还原
		data = Jt808Utils.doEscape4Receive(data, 0, data.length);
		System.out.println("转义："+HexStringUtils.toHexString(data));
		jt808Msg.setMsgBytes(data);

		// 1. 16byte 或 12byte 消息头
		Jt808MsgHeader msgHeader = Jt808MsgHeader.bytes2Object(data);
		jt808Msg.setHeader(msgHeader);

		int msgBodyByteStartIndex = 12;
		// 2. 消息体
		// 有子包信息,消息体起始字节后移四个字节:消息包总数(word(16))+包序号(word(16))
		if (msgHeader.isHasSubPackage()) {
			msgBodyByteStartIndex = 16;
		}

		byte[] tmp = new byte[msgHeader.getMsgBodyLength()];
		System.arraycopy(data, msgBodyByteStartIndex, tmp, 0, tmp.length);
		jt808Msg.setMsgBodyBytes(tmp);

		// 3. 去掉分隔符之后，最后一位就是校验码
		int checkSumInPkg = data[data.length - 1];
		int calculatedCheckSum = Jt808Utils.getCheckSum(data, 0, data.length - 1);
		jt808Msg.setCheckSum(checkSumInPkg);
		if (checkSumInPkg != calculatedCheckSum) {
			log.warn("Check code illegal,msgid:{},pkg:{},calculated:{}", msgHeader.getMsgId(), checkSumInPkg, calculatedCheckSum);
		} else {
			out.add(jt808Msg);
		}

	}

}
